<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        var A = [
            { _id: 1 },
            { _id: 2, parent: 1 },
            { _id: 3, parent: 1 },
            { _id: 4, parent: 2 },
            { _id: 5, parent: 3 },
        ]

        var B = [{
            _id: 1,
            children: [
                {
                    _id: 2, parent: 1,
                    children: [{ _id: 4, parent: 2 }]
                },
                {
                    _id: 3, parent: 1,
                    children: [{ _id: 5, parent: 3 }]
                }]
        }]


        function convertToB(array, parentId) {
            let result = [];
            for (const item of array) {
                if (item.parent === parentId) {
                    item.children = convertToB(array, item._id);
                    result.push(item);
                }
            }
            return result;
        }
        const resultB = convertToB(A, undefined);
        console.log(resultB);

        function convertToA(arr, result) {
            arr.forEach(element => {
                if (element.children) {
                    convertToA(element.children, result)
                }
                delete element.children
                result.push(element)
            });
            return result
        }
        const resultA = convertToA(B, []);
        console.log(resultA);
    </script>
</body>

</html>